<template>
  <div class="create-production-plan">
    <div class="page-header">
      <h2>新增生产计划</h2>
    </div>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="production-plan-form"
    >
      <div class="main-layout">
        <!-- 左侧四个模块 -->
        <div class="left-panel">
          <!-- 1. 基础信息 -->
          <el-card class="form-section" header="基础信息">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="计划主题" prop="planSubject">
                  <el-input
                    v-model="formData.planSubject"
                    placeholder="请输入计划主题"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划单号" prop="planNumber">
                  <el-input
                    v-model="formData.planNumber"
                    placeholder="请输入计划单号"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单据日期" prop="documentDate">
                  <el-date-picker
                    v-model="formData.documentDate"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="关联项目" prop="projectId">
                  <el-select
                    v-model="formData.projectId"
                    placeholder="请选择项目名称"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="project in allProjects"
                      :key="project.id"
                      :label="project.projectName"
                      :value="project.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="销售订单" prop="salesOrderId">
                  <el-select
                    v-model="formData.salesOrderId"
                    placeholder="请选择销售订单"
                    clearable
                    style="width: 100%"
                    :disabled="formData.isBindSalesOrder"
                    @change="handleSalesOrderChange"
                  >
                    <el-option
                      v-for="order in allSalesOrders"
                      :key="order.id"
                      :label="`${order.salesOrderNumber} - ${order.salesOrderSubject}`"
                      :value="order.id"
                    />
                  </el-select>
                  <el-checkbox
                    v-model="formData.isBindSalesOrder"
                    style="margin-left: 20px"
                    @change="handleBindSalesOrderChange"
                  >
                    不绑定销售订单
                  </el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input
                    v-model="formData.remarks"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 2. 生产物品 -->
          <el-card class="form-section" header="生产物品">
            <div class="section-header">
              <el-button type="primary" @click="addProductionItem">
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
              <el-button type="warning" @click="removeSelectedItems" :disabled="selectedItems.length === 0">
                <el-icon><Delete /></el-icon>
                移除
              </el-button>
            </div>

            <el-table
              :data="formData.productedItems"
              border
              style="width: 100%"
              @selection-change="handleProductionItemSelectionChange"
              size="small"
            >
              <el-table-column type="selection" width="45" />
              <el-table-column prop="index" label="序号" width="50" />
              <el-table-column label="物品编号" width="100">
                <template #default="{ row }">
                  <el-input v-model="row.itemNumber" placeholder="请输入" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="物品名称" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.itemName" placeholder="请输入" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="规格型号" width="100">
                <template #default="{ row }">
                  <el-input v-model="row.specificationModel" placeholder="请输入" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="单位" width="60">
                <template #default="{ row }">
                  <el-input v-model="row.unit" placeholder="请输入" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="物品类别" width="80">
                <template #default="{ row }">
                  <el-input v-model="row.itemCategory" placeholder="请输入" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="物品分类" width="80">
                <template #default="{ row }">
                  <el-input v-model="row.itemClassification" placeholder="请输入" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="品牌" width="80">
                <template #default="{ row }">
                  <el-input v-model="row.brand" placeholder="请输入" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="*数量" width="70">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.quantity"
                    :min="0"
                    placeholder="请输入"
                    size="small"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="详情日期" width="100">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.detailDate"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    size="small"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="主单位数量" width="90">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.mainUnitQuantity"
                    :min="0"
                    placeholder="请输入"
                    size="small"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="备注" width="100">
                <template #default="{ row }">
                  <el-input v-model="row.remarks" placeholder="请输入备注" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="70">
                <template #default="{ row, $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeProductionItem($index)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="total-section">
              <span class="total-label">合计：</span>
              <span class="total-value">总量: {{ totalQuantity }}</span>
            </div>
          </el-card>

          <!-- 3. 附件 -->
          <el-card class="form-section" header="附件">
            <div class="upload-section">
              <el-upload
                ref="uploadRef"
                :action="uploadAction"
                :headers="uploadHeaders"
                :data="uploadData"
                :before-upload="beforeUpload"
                :on-success="onUploadSuccess"
                :on-error="onUploadError"
                :file-list="fileList"
                :auto-upload="false"
                drag
                multiple
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  点击上传/拖拽到此区域
                </div>
              </el-upload>
            </div>

            <div v-if="formData.attachments.length > 0" class="attachment-list">
              <h4>已上传的附件：</h4>
              <el-table :data="formData.attachments" border style="width: 100%">
                <el-table-column prop="fileName" label="文件名" />
                <el-table-column prop="fileSize" label="文件大小" width="120">
                  <template #default="{ row }">
                    {{ formatFileSize(row.fileSize) }}
                  </template>
                </el-table-column>
                <el-table-column prop="fileType" label="文件类型" width="100" />
                <el-table-column label="操作" width="200">
                  <template #default="{ row, $index }">
                    <el-button
                      type="primary"
                      size="small"
                      @click="reuploadFile($index)"
                    >
                      重新上传
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      @click="removeAttachment($index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>

          <!-- 4. 选择物品 -->
          <el-card class="form-section" header="选择物品">
            <div class="section-header">
              <el-button type="success" @click="showItemDialog = true">
                <el-icon><Plus /></el-icon>
                选择物品
              </el-button>
              <el-button type="warning" @click="removeSelectedItemsFromSelectItems" :disabled="selectedItems.length === 0">
                <el-icon><Delete /></el-icon>
                移除
              </el-button>
            </div>

            <el-table
              :data="selectedItems"
              border
              style="width: 100%"
              @selection-change="handleSelectedItemsChange"
              size="small"
            >
              <el-table-column type="selection" width="45" />
              <el-table-column prop="itemNumber" label="物品编号" width="100" />
              <el-table-column prop="itemName" label="物品名称" width="120" />
              <el-table-column prop="specificationModel" label="规格型号" width="100" />
              <el-table-column prop="unit" label="单位" width="60" />
              <el-table-column prop="itemCategory" label="物品类别" width="80" />
              <el-table-column prop="itemClassification" label="物品分类" width="80" />
              <el-table-column prop="brand" label="品牌" width="80" />
              <el-table-column prop="totalInventory" label="总库存" width="70" />
              <el-table-column prop="purchaseUnitPrice" label="采购单价" width="80" />
              <el-table-column prop="salesUnitPrice" label="销售单价" width="80" />
            </el-table>
          </el-card>
        </div>

        <!-- 右侧两个模块 -->
        <div class="right-panel">
          <!-- 1. 选择销售订单 -->
          <el-card class="form-section" header="选择销售订单">
            <div class="section-header">
              <el-button type="primary" @click="showSalesOrderDialog = true">
                <el-icon><Plus /></el-icon>
                选择销售订单
              </el-button>
            </div>

            <div v-if="selectedSalesOrders.length > 0" class="selected-items">
              <h4>已选择的销售订单：</h4>
              <el-table :data="selectedSalesOrders" border style="width: 100%" size="small">
                <el-table-column prop="salesOrderNumber" label="销售单号" width="100" />
                <el-table-column prop="salesOrderSubject" label="销售订单主题" width="150" />
                <el-table-column prop="customerName" label="客户名称" width="120" />
                <el-table-column prop="salesDate" label="销售日期" width="100" />
                <el-table-column prop="purchaseStatus" label="采购状态" width="80" />
                <el-table-column label="操作" width="150">
                  <template #default="{ row }">
                    <el-button
                      type="primary"
                      size="small"
                      @click="viewSalesOrderItems(row)"
                    >
                      查看物品
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      @click="removeSalesOrder(row)"
                    >
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>

          <!-- 2. 销售订单物品列表 -->
          <el-card class="form-section" header="销售订单物品列表">
            <div v-if="currentSalesOrder && salesOrderItemData.length > 0" class="selected-items">
              <h4>当前销售订单：{{ currentSalesOrder.salesOrderNumber }} - {{ currentSalesOrder.salesOrderSubject }}</h4>
              <el-table :data="salesOrderItemData" border style="width: 100%" size="small">
                <el-table-column prop="itemNumber" label="物品编号" width="100" />
                <el-table-column prop="itemName" label="物品名称" width="120" />
                <el-table-column prop="specificationModel" label="规格型号" width="100" />
                <el-table-column prop="unit" label="单位" width="60" />
                <el-table-column prop="itemCategory" label="物品类别" width="80" />
                <el-table-column prop="itemClassification" label="物品分类" width="80" />
                <el-table-column prop="brand" label="品牌" width="80" />
                <el-table-column prop="totalInventory" label="库存" width="60" />
                <el-table-column prop="salesQuantity" label="销售数量" width="80" />
                <el-table-column label="操作" width="100">
                  <template #default="{ row }">
                    <el-button
                      type="primary"
                      size="small"
                      @click="addToProductionItems(row)"
                    >
                      添加到生产物品
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="empty-state">
              <p>请先选择销售订单查看物品列表</p>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </div>
    </el-form>

    <!-- 选择销售订单弹窗 -->
    <el-dialog
      v-model="showSalesOrderDialog"
      title="选择销售订单"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="search-form">
          <el-form :model="salesOrderQuery" inline>
            <el-form-item label="销售单号/主题">
              <el-input
                v-model="salesOrderQuery.salesOrderNumberOrSubject"
                placeholder="请输入销售单号/主题"
                clearable
              />
            </el-form-item>
            <el-form-item label="客户名称">
              <el-input
                v-model="salesOrderQuery.customerName"
                placeholder="请输入客户名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="销售日期">
              <el-date-picker
                v-model="salesOrderDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="采购状态">
              <el-select v-model="salesOrderQuery.purchaseStatus" placeholder="请选择" clearable>
                <el-option label="未完成" value="未完成" />
                <el-option label="已完成" value="已完成" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSalesOrders">查询</el-button>
              <el-button @click="resetSalesOrderQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          :data="salesOrderData"
          border
          style="width: 100%"
          @selection-change="handleSalesOrderSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="salesOrderNumber" label="销售单号" width="150" />
          <el-table-column prop="salesOrderSubject" label="销售订单主题" />
          <el-table-column prop="customerName" label="客户名称" width="150" />
          <el-table-column prop="salesDate" label="销售日期" width="120" />
          <el-table-column prop="purchaseStatus" label="采购状态" width="100" />
          <el-table-column prop="itemSummary" label="物品概要" width="200" />
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="salesOrderQuery.pageIndex"
            v-model:page-size="salesOrderQuery.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="salesOrderTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSalesOrderSizeChange"
            @current-change="handleSalesOrderCurrentChange"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSalesOrderDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSalesOrderSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 销售订单物品列表弹窗 -->
    <el-dialog
      v-model="showSalesOrderItemsDialog"
      :title="`销售订单${currentSalesOrder?.salesOrderNumber}物品列表`"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="search-form">
          <el-form :model="salesOrderItemQuery" inline>
            <el-form-item label="物品编号/名称/规格型号">
              <el-input
                v-model="salesOrderItemQuery.itemNumberOrNameOrModel"
                placeholder="请输入物品编号/名称/规格型号"
                clearable
              />
            </el-form-item>
            <el-form-item label="物品类别">
              <el-select v-model="salesOrderItemQuery.itemCategory" placeholder="请选择" clearable>
                <el-option label="原材料" value="原材料" />
                <el-option label="半成品" value="半成品" />
                <el-option label="成品" value="成品" />
              </el-select>
            </el-form-item>
            <el-form-item label="物品分类">
              <el-select v-model="salesOrderItemQuery.itemClassification" placeholder="请选择" clearable>
                <el-option label="电子产品" value="电子产品" />
                <el-option label="家具" value="家具" />
                <el-option label="衣物" value="衣物" />
                <el-option label="食品" value="食品" />
                <el-option label="化妆品" value="化妆品" />
              </el-select>
            </el-form-item>
            <el-form-item label="库存状态">
              <el-select v-model="salesOrderItemQuery.inventoryStatus" placeholder="请选择" clearable>
                <el-option label="有库存" value="有库存" />
                <el-option label="无库存" value="无库存" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSalesOrderItems">查询</el-button>
              <el-button @click="resetSalesOrderItemQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          :data="salesOrderItemData"
          border
          style="width: 100%"
          @selection-change="handleSalesOrderItemSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="itemNumber" label="物品编号" width="150" />
          <el-table-column prop="itemName" label="物品名称" />
          <el-table-column prop="specificationModel" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="itemCategory" label="物品类别" width="100" />
          <el-table-column prop="itemClassification" label="物品分类" width="100" />
          <el-table-column prop="brand" label="品牌" width="120" />
          <el-table-column prop="totalInventory" label="库存" width="80" />
          <el-table-column prop="salesQuantity" label="销售数量" width="100" />
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="salesOrderItemQuery.pageIndex"
            v-model:page-size="salesOrderItemQuery.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="salesOrderItemTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSalesOrderItemSizeChange"
            @current-change="handleSalesOrderItemCurrentChange"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSalesOrderItemsDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择物品弹窗 -->
    <el-dialog
      v-model="showItemDialog"
      title="选择物品"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="search-form">
          <el-form :model="itemQuery" inline>
            <el-form-item label="物品编号/名称/规格型号">
              <el-input
                v-model="itemQuery.itemNumberOrNameOrModel"
                placeholder="请输入物品编号/名称/规格型号"
                clearable
              />
            </el-form-item>
            <el-form-item label="物品类别">
              <el-select v-model="itemQuery.itemCategory" placeholder="请选择" clearable>
                <el-option label="原材料" value="原材料" />
                <el-option label="半成品" value="半成品" />
                <el-option label="成品" value="成品" />
              </el-select>
            </el-form-item>
            <el-form-item label="物品分类">
              <el-select v-model="itemQuery.itemClassification" placeholder="请选择" clearable>
                <el-option label="电子产品" value="电子产品" />
                <el-option label="家具" value="家具" />
                <el-option label="衣物" value="衣物" />
                <el-option label="食品" value="食品" />
                <el-option label="化妆品" value="化妆品" />
              </el-select>
            </el-form-item>
            <el-form-item label="库存状态">
              <el-select v-model="itemQuery.inventoryStatus" placeholder="请选择" clearable>
                <el-option label="有库存" value="有库存" />
                <el-option label="无库存" value="无库存" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchItems">查询</el-button>
              <el-button @click="resetItemQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          :data="itemData"
          border
          style="width: 100%"
          @selection-change="handleItemSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="itemNumber" label="物品编号" width="150" />
          <el-table-column prop="itemName" label="物品名称" />
          <el-table-column prop="specificationModel" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="itemCategory" label="物品类别" width="100" />
          <el-table-column prop="itemClassification" label="物品分类" width="100" />
          <el-table-column prop="brand" label="品牌" width="120" />
          <el-table-column prop="totalInventory" label="库存" width="80" />
          <el-table-column prop="purchaseUnitPrice" label="采购单价" width="100" />
          <el-table-column prop="salesUnitPrice" label="销售单价" width="100" />
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="itemQuery.pageIndex"
            v-model:page-size="itemQuery.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="itemTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleItemSizeChange"
            @current-change="handleItemCurrentChange"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showItemDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmItemSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type UploadInstance } from 'element-plus'
import { Plus, Delete, UploadFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getDefaultYearRange } from '@/utils/dateUtils'
import {
  createProductionPlan,
  uploadFile,
  getItemPage,
  getSalesOrderPage,
  getSalesOrderItems,
  getAllProjects
} from '@/services/productionPlan'
import type {
  CreateProductionPlanDto,
  ProductionItem,
  Attachment,
  ItemQueryDto,
  Item,
  SalesOrderQueryDto,
  SalesOrder,
  SalesOrderItemQueryDto,
  SalesOrderItem
} from '@/types/productionPlan'
import type { Project } from '@/types/project'

const router = useRouter()
const formRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()

// 表单数据
const formData = reactive<CreateProductionPlanDto>({
  planNumber: '',
  planSubject: '',
  documentDate: '',
  salesOrderId: 0,
  projectId: 0,
  remarks: '',
  isBindSalesOrder: true,
  productedItems: [],
  attachments: [],
  selectedItemIds: [],
  selectedSalesOrderIds: []
})

// 表单验证规则
const formRules = {
  planSubject: [
    { required: true, message: '请输入计划主题', trigger: 'blur' }
  ],
  planNumber: [
    { required: true, message: '请输入计划单号', trigger: 'blur' }
  ],
  documentDate: [
    { required: true, message: '请选择单据日期', trigger: 'change' }
  ]
}

// 项目选项
const allProjects = ref<Project[]>([])

// 已选择的销售订单
const selectedSalesOrders = ref<SalesOrder[]>([])

// 所有销售订单（用于下拉框）
const allSalesOrders = ref<SalesOrder[]>([])

// 当前销售订单的物品
const selectedSalesOrderItems = ref<SalesOrderItem[]>([])

// 弹窗控制
const showSalesOrderDialog = ref(false)
const showSalesOrderItemsDialog = ref(false)
const showItemDialog = ref(false)

// 销售订单查询
const salesOrderQuery = reactive<SalesOrderQueryDto>({
  salesOrderNumberOrSubject: '',
  customerName: '',
  salesDateStart: getDefaultYearRange(2025)[0],
  salesDateEnd: getDefaultYearRange(2025)[1],
  purchaseStatus: '',
  pageIndex: 1,
  pageSize: 10
})

const salesOrderDateRange = ref<[string, string]>(getDefaultYearRange(2025))
const salesOrderData = ref<SalesOrder[]>([])
const salesOrderTotal = ref(0)
const selectedSalesOrdersForDialog = ref<SalesOrder[]>([])

// 销售订单物品查询
const salesOrderItemQuery = reactive<SalesOrderItemQueryDto>({
  salesOrderId: 0,
  itemNumberOrNameOrModel: '',
  itemCategory: '',
  itemClassification: '',
  inventoryStatus: '',
  pageIndex: 1,
  pageSize: 10
})

const salesOrderItemData = ref<SalesOrderItem[]>([])
const salesOrderItemTotal = ref(0)
const currentSalesOrder = ref<SalesOrder>()

// 物品查询
const itemQuery = reactive<ItemQueryDto>({
  itemNumberOrNameOrModel: '',
  itemCategory: '',
  itemClassification: '',
  inventoryStatus: '',
  pageIndex: 1,
  pageSize: 10
})

const itemData = ref<Item[]>([])
const itemTotal = ref(0)
const selectedItemsForDialog = ref<Item[]>([])

// 选择物品相关
const selectedItems = ref<Item[]>([])

// 生产物品相关
const selectedProductionItems = ref<ProductionItem[]>([])

// 文件上传
const fileList = ref<any[]>([])
const submitting = ref(false)

// 计算属性
const totalQuantity = computed(() => {
  return formData.productedItems.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const uploadAction = computed(() => {
  return 'https://localhost/api/ProductionPlan/upload'
})

const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return {
    Authorization: `Bearer ${token}`
  }
})

const uploadData = computed(() => {
  return {
    productionPlanId: 0 // 临时ID，创建成功后更新
  }
})

// 方法
const addProductionItem = () => {
  const newItem: ProductionItem = {
    itemNumber: '',
    itemName: '',
    specificationModel: '',
    unit: '',
    itemCategory: '',
    itemClassification: '',
    brand: '',
    quantity: 0,
    detailDate: '',
    mainUnitQuantity: 0,
    remarks: ''
  }
  
  // 添加序号
  newItem.index = formData.productedItems.length + 1
  
  formData.productedItems.push(newItem)
}

const removeProductionItem = (index: number) => {
  formData.productedItems.splice(index, 1)
  // 重新计算序号
  formData.productedItems.forEach((item, idx) => {
    item.index = idx + 1
  })
}

const handleProductionItemSelectionChange = (selection: ProductionItem[]) => {
  selectedProductionItems.value = selection
}

const removeSelectedItems = () => {
  const indices = selectedProductionItems.value.map(item => 
    formData.productedItems.findIndex(pItem => pItem === item)
  ).sort((a, b) => b - a)
  
  indices.forEach(index => {
    if (index !== -1) {
      formData.productedItems.splice(index, 1)
    }
  })
  
  // 重新计算序号
  formData.productedItems.forEach((item, idx) => {
    item.index = idx + 1
  })
  
  selectedProductionItems.value = []
}

// 销售订单相关方法
const handleSalesOrderChange = async (salesOrderId: number) => {
  if (salesOrderId && !formData.isBindSalesOrder) {
    // 获取销售订单的物品列表
    try {
      const query: SalesOrderItemQueryDto = {
        salesOrderId,
        itemNumberOrNameOrModel: '',
        itemCategory: '',
        itemClassification: '',
        inventoryStatus: '',
        pageIndex: 1,
        pageSize: 100 // 获取所有物品
      }
      
      const response = await getSalesOrderItems(query)
      selectedSalesOrderItems.value = response.pageData
    } catch (error) {
      console.error('获取销售订单物品失败:', error)
      ElMessage.error('获取销售订单物品失败')
    }
  } else {
    selectedSalesOrderItems.value = []
  }
}

const handleBindSalesOrderChange = (checked: boolean) => {
  if (checked) {
    // 如果不绑定销售订单，清空相关数据
    formData.salesOrderId = 0
    selectedSalesOrderItems.value = []
    salesOrderItemData.value = []
    currentSalesOrder.value = undefined
  }
}

const addToProductionItems = (item: SalesOrderItem) => {
  // 将销售订单物品添加到生产物品列表
  const newProductionItem: ProductionItem = {
    itemNumber: item.itemNumber,
    itemName: item.itemName,
    specificationModel: item.specificationModel,
    unit: item.unit,
    itemCategory: item.itemCategory,
    itemClassification: item.itemClassification,
    brand: item.brand,
    quantity: item.salesQuantity || 0,
    detailDate: new Date().toISOString().split('T')[0],
    mainUnitQuantity: item.salesQuantity || 0,
    remarks: `来自销售订单: ${item.salesQuantity || 0}个`
  }
  
  // 添加序号
  newProductionItem.index = formData.productedItems.length + 1
  
  formData.productedItems.push(newProductionItem)
  ElMessage.success('已添加到生产物品列表')
}

const searchSalesOrders = async () => {
  try {
    if (salesOrderDateRange.value && salesOrderDateRange.value.length === 2) {
      salesOrderQuery.salesDateStart = salesOrderDateRange.value[0]
      salesOrderQuery.salesDateEnd = salesOrderDateRange.value[1]
    }
    
    const response = await getSalesOrderPage(salesOrderQuery)
    // 直接使用响应数据，因为API函数已经处理了数据结构
    salesOrderData.value = response.pageData
    salesOrderTotal.value = response.totaCount
  } catch (error) {
    console.error('查询销售订单失败:', error)
    ElMessage.error('查询失败，请重试')
  }
}

const resetSalesOrderQuery = () => {
  Object.assign(salesOrderQuery, {
    salesOrderNumberOrSubject: '',
    customerName: '',
    salesDateStart: getDefaultYearRange(2025)[0],
    salesDateEnd: getDefaultYearRange(2025)[1],
    purchaseStatus: '',
    pageIndex: 1,
    pageSize: 10
  })
  salesOrderDateRange.value = getDefaultYearRange(2025)
  searchSalesOrders()
}

const handleSalesOrderSelectionChange = (selection: SalesOrder[]) => {
  selectedSalesOrdersForDialog.value = selection
}

const confirmSalesOrderSelection = () => {
  selectedSalesOrders.value = [...selectedSalesOrders.value, ...selectedSalesOrdersForDialog.value]
  formData.selectedSalesOrderIds = selectedSalesOrders.value.map(order => order.id)
  showSalesOrderDialog.value = false
  selectedSalesOrdersForDialog.value = []
}

const removeSalesOrder = (salesOrder: SalesOrder) => {
  const index = selectedSalesOrders.value.findIndex(order => order.id === salesOrder.id)
  if (index !== -1) {
    selectedSalesOrders.value.splice(index, 1)
    formData.selectedSalesOrderIds = selectedSalesOrders.value.map(order => order.id)
  }
}

const viewSalesOrderItems = async (salesOrder: SalesOrder) => {
  currentSalesOrder.value = salesOrder
  salesOrderItemQuery.salesOrderId = salesOrder.id
  await searchSalesOrderItems()
  showSalesOrderItemsDialog.value = true
}

const searchSalesOrderItems = async () => {
  try {
    const response = await getSalesOrderItems(salesOrderItemQuery)
    // 直接使用响应数据，因为API函数已经处理了数据结构
    salesOrderItemData.value = response.pageData
    salesOrderItemTotal.value = response.totaCount
  } catch (error) {
    console.error('查询销售订单物品失败:', error)
    ElMessage.error('查询失败，请重试')
  }
}

const resetSalesOrderItemQuery = () => {
  Object.assign(salesOrderItemQuery, {
    itemNumberOrNameOrModel: '',
    itemCategory: '',
    itemClassification: '',
    inventoryStatus: '',
    pageIndex: 1,
    pageSize: 10
  })
  searchSalesOrderItems()
}

const handleSalesOrderItemSelectionChange = (selection: SalesOrderItem[]) => {
  selectedSalesOrderItems.value = selection
}

const handleSalesOrderItemSizeChange = (size: number) => {
  salesOrderItemQuery.pageSize = size
  searchSalesOrderItems()
}

const handleSalesOrderItemCurrentChange = (page: number) => {
  salesOrderItemQuery.pageIndex = page
  searchSalesOrderItems()
}

const handleSalesOrderSizeChange = (size: number) => {
  salesOrderQuery.pageSize = size
  searchSalesOrders()
}

const handleSalesOrderCurrentChange = (page: number) => {
  salesOrderQuery.pageIndex = page
  searchSalesOrders()
}

// 物品相关方法
const searchItems = async () => {
  try {
    const response = await getItemPage(itemQuery)
    // 直接使用响应数据，因为API函数已经处理了数据结构
    itemData.value = response.pageData
    itemTotal.value = response.totaCount
  } catch (error) {
    console.error('查询物品失败:', error)
    ElMessage.error('查询失败，请重试')
  }
}

const resetItemQuery = () => {
  Object.assign(itemQuery, {
    itemNumberOrNameOrModel: '',
    itemCategory: '',
    itemClassification: '',
    inventoryStatus: '',
    pageIndex: 1,
    pageSize: 10
  })
  searchItems()
}

const handleItemSelectionChange = (selection: Item[]) => {
  selectedItemsForDialog.value = selection
}

const handleSelectedItemsChange = (selection: Item[]) => {
  selectedItemsForDialog.value = selection
}

const confirmItemSelection = () => {
  // 将选择的物品添加到选择物品模块
  selectedItems.value = [...selectedItems.value, ...selectedItemsForDialog.value]
  showItemDialog.value = false
  selectedItemsForDialog.value = []
  ElMessage.success(`已选择 ${selectedItemsForDialog.value.length} 个物品`)
}

const removeSelectedItemsFromSelectItems = () => {
  // 移除选择物品模块中选中的物品
  const indices = selectedItemsForDialog.value.map(item => 
    selectedItems.value.findIndex(sItem => sItem === item)
  ).sort((a, b) => b - a)
  
  indices.forEach(index => {
    if (index > -1) {
      selectedItems.value.splice(index, 1)
    }
  })
  
  selectedItemsForDialog.value = []
  ElMessage.success('已移除选中的物品')
}

const handleItemSizeChange = (size: number) => {
  itemQuery.pageSize = size
  searchItems()
}

const handleItemCurrentChange = (page: number) => {
  itemQuery.pageIndex = page
  searchItems()
}

// 文件上传相关方法
const beforeUpload = (file: File) => {
  // 这里可以添加文件类型和大小验证
  return true
}

const onUploadSuccess = (response: any, file: any) => {
  if (response.code === 200) {
    const attachment: Attachment = {
      fileName: file.name,
      filePath: response.data,
      fileSize: file.size,
      fileType: file.type
    }
    formData.attachments.push(attachment)
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(response.msg || '文件上传失败')
  }
}

const onUploadError = (error: any) => {
  ElMessage.error('文件上传失败，请重试')
}

const reuploadFile = (index: number) => {
  // 重新上传逻辑
  ElMessage.info('请重新选择文件上传')
}

const removeAttachment = (index: number) => {
  formData.attachments.splice(index, 1)
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 验证生产物品
    if (formData.productedItems.length === 0) {
      ElMessage.warning('请至少添加一个生产物品')
      return
    }
    
    // 验证必填字段
    for (const item of formData.productedItems) {
      if (!item.quantity || item.quantity <= 0) {
        ElMessage.warning('请填写所有生产物品的数量')
        return
      }
    }
    
    const response = await createProductionPlan(formData)
    if (response.code === 200) {
      ElMessage.success('生产计划创建成功')
      router.push('/production-plan')
    } else {
      ElMessage.error(response.msg || '创建失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  router.push('/production-plan')
}

// 初始化
onMounted(async () => {
  // 设置默认日期为今天
  const today = new Date()
  formData.documentDate = today.toISOString().split('T')[0]
  
  // 初始化查询
  await searchSalesOrders()
  await searchItems()
  
  // 加载所有项目到下拉框
  try {
    const projects = await getAllProjects()
    allProjects.value = projects
  } catch (error) {
    console.error('加载项目失败:', error)
    ElMessage.error('加载项目失败')
  }

  try {
    const query: SalesOrderQueryDto = {
      salesOrderNumberOrSubject: '',
      customerName: '',
      salesDateStart: getDefaultYearRange(2025)[0],
      salesDateEnd: getDefaultYearRange(2025)[1],
      purchaseStatus: '',
      pageIndex: 1,
      pageSize: 1000 // 获取所有销售订单
    }
    
    const response = await getSalesOrderPage(query)
    allSalesOrders.value = response.pageData
  } catch (error) {
    console.error('加载销售订单失败:', error)
    ElMessage.error('加载销售订单失败')
  }
})
</script>

<style scoped>
.create-production-plan {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.main-layout {
  display: flex;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.left-panel {
  flex: 0 0 60%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.right-panel {
  flex: 0 0 40%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-section {
  flex: 1;
  min-height: 0;
}

/* 确保表格内容不会溢出 */
.form-section .el-table {
  width: 100%;
  font-size: 12px;
}

.form-section .el-table .cell {
  padding: 8px;
}

/* 调整列宽度，确保内容完整显示 */
.form-section .el-table .el-table__column {
  min-width: 80px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-layout {
    flex-direction: column;
    max-width: 100%;
  }
  
  .left-panel, .right-panel {
    flex: 1;
  }
}

.form-section :deep(.el-card__header) {
  background-color: #f8f9fa;
  font-weight: bold;
}

.section-header {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.selected-items {
  margin-top: 20px;
}

.selected-items h4 {
  margin-bottom: 15px;
  color: #666;
}

.total-section {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.total-label {
  font-weight: bold;
  margin-right: 10px;
}

.total-value {
  color: #409eff;
  font-weight: bold;
}

.upload-section {
  margin-bottom: 20px;
}

.attachment-list {
  margin-top: 20px;
}

.attachment-list h4 {
  margin-bottom: 15px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 20px;
  color: #999;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding: 20px 0;
}

.dialog-content {
  padding: 20px 0;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
}

:deep(.el-upload__text) {
  margin-top: 10px;
  color: #666;
}
</style> 